﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace GRMS.App_Code
{
    public class ActionSequencer
    {
        public bool IsActive;
        public bool Defend;
        public List<string> ActiveActors;

        Session sesh;

        SortedDictionary<int, string> ActorList;
        SortedDictionary<int, string>.Enumerator CurrentActorEnum;

        public ActionSequencer(string[] actors, Session sesh)
        {
            char[] split = { '+' };
            this.sesh = sesh;
            this.IsActive = true;
            this.Defend = false;

            RollInitiative(actors, sesh);
            this.ActorList.OrderByDescending(kvp => kvp.Key);
            this.CurrentActorEnum = ActorList.GetEnumerator();
        }

        private void RollInitiative(string[] actors, Session sesh)
        {
            ActorList = new SortedDictionary<int, string>();
            ActiveActors = new List<string>();

            foreach (string actor in actors)
            {
                if (!sesh.HasCharacter(actor))
                    continue;

                Int32 Init = Initiative(actor, sesh);

                if (ActorList.ContainsKey(Init))
                {
                    RollInitiative(actors, sesh);
                    break;
                }
                else
                {
                    this.ActorList.Add(Init, actor);
                    ActiveActors.Add(actor);
                }
            }
        }

        private Int32 Initiative(string actor, Session sesh)
        {
            ActionEventFactory AEF = new ActionEventFactory(sesh);
            ActionEventHandler AEH = new ActionEventHandler(sesh);

            ActionEventRequest AER = sesh.GetCharacter(actor).GetEventRequest("Initiative");
            ActionEvent AE = AEF.GenerateActionEvent(AER);
            return Int32.Parse(AEH.ProcessActionEvent(AE).Replace("<br/>", ""));
        }

        public string Header()
        {
            string result = "";
            char[] trim = { ' ', '|' };

            foreach (KeyValuePair<int, string> actor in ActorList)
            {
                result += string.Format("{0}: {1} | ", actor.Value, actor.Key);
            }
            result = result.TrimEnd(trim);
            CurrentActorEnum.MoveNext();
            result += string.Format("<br/>Current Actor: {0}", CurrentActorEnum.Current.Value);

            return result;
        }

        public string CurrentActor()
        {
            return CurrentActorEnum.Current.Value;
        }

        public bool Next()
        {
            RollInitiative(ActiveActors.ToArray(), sesh);
            this.ActorList.OrderByDescending(kvp => kvp.Key);
            this.CurrentActorEnum = ActorList.GetEnumerator();

            return CurrentActorEnum.MoveNext();
        }
    }
}
